#include "muduo/proto/codec.h"
#include "muduo/proto/dispatcher.h"
#include "request.pb.h"

#include "muduo/base/Logging.h"
#include "muduo/base/Mutex.h"
#include "muduo/net/EventLoop.h"
#include "muduo/net/TcpClient.h"

#include "muduo/net/EventLoopThread.h"
#include "muduo/base/CountDownLatch.h"

#include <iostream>
#include <functional>

class Client
{
public:
    typedef std::shared_ptr<google::protobuf::Message> MessagePtr;
    typedef std::shared_ptr<Req::TranslateResponse> TranslateResponsePtr;
    typedef std::shared_ptr<Req::AddResponse> AddResponsePtr;

    Client(const std::string& s_ip, int s_port)
    : _latch(1),
      _client(_loopthread.startLoop(), muduo::net::InetAddress(s_ip, s_port), "Client"),
      _dispatcher(std::bind(&Client::onUnknownMessage, this, 
        std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)),
      _codec(std::bind(&ProtobufDispatcher::onProtobufMessage, &_dispatcher, 
        std::placeholders::_1, std::placeholders::_2, std::placeholders::_3))
    {
        // 注册事件处理函数
        _dispatcher.registerMessageCallback<Req::TranslateResponse>(std::bind(&Client::onTranslate, 
            this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
        _dispatcher.registerMessageCallback<Req::AddResponse>(std::bind(&Client::onAdd, this, 
            std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
        
        // 告知客户端，接收到什么事件应该如何处理
        _client.setConnectionCallback(
            std::bind(&Client::onConnection, this, std::placeholders::_1));
        _client.setMessageCallback(std::bind(&ProtobufCodec::onMessage, &_codec, 
            std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
    }

    void connect()
    {
        _client.connect();
        // 发送连接后进行阻塞，等待连接成功后被唤醒
        _latch.wait();
    }

    void Translate(const std::string& str)
    {
        Req::TranslateRequest req;
        req.set_msg(str);
        send(&req);
    }

    void Add(int num1, int num2)
    {
        Req::AddRequest req;
        req.set_num1(num1);
        req.set_num2(num2);
        send(&req);
    }

private:
    bool send(const google::protobuf::Message* message)
    {
        if (_conn->connected())
        {
            _codec.send(_conn, *message);
            return true;
        }
        return false;
    }
    void onUnknownMessage(const muduo::net::TcpConnectionPtr&,
                        const MessagePtr& message,
                        muduo::Timestamp)
    {
        LOG_INFO << "onUnknownMessage: " << message->GetTypeName();
    }

    void onTranslate(const muduo::net::TcpConnectionPtr& conn,
                            const TranslateResponsePtr& message,
                            muduo::Timestamp)
    {
        std::cout << "翻译结果：" << message->msg() << std::endl;
    }

    void onAdd(const muduo::net::TcpConnectionPtr& conn,
                        const AddResponsePtr& message,
                        muduo::Timestamp)
    {
        std::cout << "加法结果：" << message->result() << std::endl;
    }

    void onConnection(const muduo::net::TcpConnectionPtr& conn)
    {
        if (conn->connected())
        {
            // 唤醒主线程
            _latch.countDown();
            // 连接建立成功
            _conn = conn;
        }
        else
        {
            // 连接断开
            _conn.reset();
        }
    }
private:
    muduo::CountDownLatch _latch; // connect 和 send 实现同步
    muduo::net::EventLoopThread _loopthread; // 异步循环处理线程
    muduo::net::TcpClient _client; // 客户端
    muduo::net::TcpConnectionPtr _conn; // 客户端连接
    ProtobufDispatcher _dispatcher; // 请求分发器
    ProtobufCodec _codec; // 协议处理器
};

int main()
{
    Client client("127.0.0.1", 8085);
    client.connect();

    client.Translate("hello");
    client.Add(11, 22);

    sleep(1);
    return 0;
}